package com.smart.reader.exception;


import com.smart.reader.common.R;
import com.smart.reader.enums.ExceptionResultCode;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author XiaoJunYun
 * @version 1.0
 * @date 2021/4/22 18:05
 * @desc: 异常信息统⼀拦截
 */
@RestControllerAdvice
public class CustomExceptionHandler {
    /**
     * 参数校验异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public R errorHandler(BindException ex) {
        BindingResult result = ex.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        for (ObjectError error : result.getAllErrors()) {
            errorMsg.append(error.getDefaultMessage()).append(", ");
        }
        errorMsg.delete(errorMsg.length() - 2, errorMsg.length());
        return R.fail(ExceptionResultCode.VALID_EXCEPTION.getCode(), errorMsg.toString());
    }
    /**
     * 参数校验异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R validationErrorHandler(ConstraintViolationException ex) {
        List<String> errorInformation = ex.getConstraintViolations()
                .stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.toList());
        String message = errorInformation.toString().substring(1, errorInformation.toString().length() - 1);
        return R.fail(ExceptionResultCode.VALID_EXCEPTION.getCode(), message);
    }
    /**
     * ⾃定义异常
     *
     * @param customException
     * @return
     */
    @ExceptionHandler(value = CustomException.class)
    public R customExceptionHandler(CustomException customException) {
        String message = customException.getMessage();
        return R.fail(ExceptionResultCode.EXCEPTION.getCode(), message);
    }
    /**
     * 未知异常
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public R exceptionHandler(Exception exception) {
        exception.printStackTrace();
        return R.fail(ExceptionResultCode.EXCEPTION.getCode(), ExceptionResultCode.EXCEPTION.getMsg());
    }
}
